package com.enjoylearning.auth.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.enjoylearning.auth.service.FindPasswordService;
import com.enjoylearning.base.exception.XueChengPlusException;
import com.enjoylearning.base.model.RestResponse;
import com.enjoylearning.ucenter.feignclient.CheckCodeClient;
import com.enjoylearning.ucenter.mapper.XcUserMapper;
import com.enjoylearning.ucenter.model.dto.FindPasswordParamDto;
import com.enjoylearning.ucenter.model.po.XcUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

@Service
public class FindPasswordServiceImpl implements FindPasswordService {

    @Autowired
    private CheckCodeClient checkCodeClient;
    @Autowired
    private XcUserMapper xcUserMapper;
    @Autowired
    private  PasswordEncoder passwordEncoder;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public RestResponse setNewPassword(FindPasswordParamDto findPasswordParamDto) {
        //1、校验验证码，不一致则抛出异常
        String checkcodekey = findPasswordParamDto.getCheckcodekey();
        String checkcode = findPasswordParamDto.getCheckcode();
        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        if (!verify) {
            XueChengPlusException.cast("验证码错误！");
        }
        //2、判断两次密码是否一致，不一致则抛出异常
        String password = findPasswordParamDto.getPassword();
        String confirmpwd = findPasswordParamDto.getConfirmpwd();
        if (!password.equals(confirmpwd)) {
            XueChengPlusException.cast("密码不一致");
        }
        //3、根据手机号和邮箱查询用户
        String email = findPasswordParamDto.getEmail();
        String cellphone = findPasswordParamDto.getCellphone();
        LambdaQueryWrapper<XcUser> wapper = new LambdaQueryWrapper<>();
        wapper.eq(email != null,XcUser::getEmail, email);
        wapper.eq(cellphone != null,XcUser::getCellphone, cellphone);
        XcUser xcUser = xcUserMapper.selectOne(wapper);
        //4、如果找到用户更新为新密码
        if (null == xcUser ) {
            XueChengPlusException.cast("用户未注册");
        }
        String newPassword = passwordEncoder.encode(password);
        xcUser.setPassword(newPassword);
        xcUser.setUpdateTime(LocalDateTime.now());
        xcUserMapper.updateById(xcUser);
        return new RestResponse(200,"修改成功");
    }
}
